package deviceservice.utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Arrays;
import java.util.Collection;

/**
 * Created by Jason on 2017/8/20.
 */
public class CryptoUtil {
    public static String  hash(String input)  {
        return new BASE64Encoder().encode(hash256(input));
    }
    public static String aesEncrypt(String input,String passwd)  {
        Cipher cipher ;
        String cipertext=null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, getKey(passwd));
            cipertext = new BASE64Encoder().encode(cipher.doFinal(input.getBytes("UTF-8")));

        } catch (IllegalBlockSizeException|NoSuchPaddingException | InvalidKeyException | UnsupportedEncodingException | BadPaddingException |NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return cipertext;
    }
    public static String aesDecrypt(String cipertext,String passwd)   {
        String text=null;
        try{
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, getKey(passwd));
           text= new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(cipertext)));
        }
        catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IOException | BadPaddingException | IllegalBlockSizeException e){
            e.printStackTrace();
        }
        return text;
    }
    private static byte[] hash256(String input)  {
        MessageDigest messageDigest= null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(input.getBytes());
        //
        return messageDigest.digest();
    }

    private static  SecretKeySpec getKey(String key)  {
        byte[] bitkey = Arrays.copyOf(hash256(key),32);
        return new SecretKeySpec(bitkey,"AES");

    }



}
